package com.example.aiinterview.controller;

import com.example.aiinterview.model.User;
import com.example.aiinterview.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/admin/users")
@RequiredArgsConstructor
public class UserManagementController {

    private final UserService userService;

    @GetMapping
    public String listUsers(Model model) {
        List<User> users = userService.findAllUsers();
        model.addAttribute("users", users);
        return "admin/user-list";
    }

    @GetMapping("/create")
    public String showCreateForm(Model model) {
        model.addAttribute("user", new User());
        return "admin/user-form";
    }

    @PostMapping("/create")
    public String createUser(@RequestParam String username,
                           @RequestParam String password,
                           @RequestParam String email,
                           @RequestParam String fullName,
                           @RequestParam(defaultValue = "USER") String role,
                           RedirectAttributes redirectAttributes) {
        try {
            User.Role userRole = User.Role.valueOf(role.toUpperCase());
            userService.registerNewUser(username, password, email, fullName, userRole);
            redirectAttributes.addFlashAttribute("successMessage", "用户创建成功！");
            return "redirect:/admin/users";
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
            redirectAttributes.addFlashAttribute("username", username);
            redirectAttributes.addFlashAttribute("email", email);
            redirectAttributes.addFlashAttribute("fullName", fullName);
            redirectAttributes.addFlashAttribute("role", role);
            return "redirect:/admin/users/create";
        }
    }

    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, Model model) {
        User user = userService.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在"));
        model.addAttribute("user", user);
        return "admin/user-edit";
    }

    @PostMapping("/edit/{id}")
    public String updateUser(@PathVariable Long id,
                           @RequestParam String username,
                           @RequestParam String email,
                           @RequestParam String fullName,
                           RedirectAttributes redirectAttributes) {
        try {
            userService.updateUser(id, username, email, fullName);
            redirectAttributes.addFlashAttribute("successMessage", "用户更新成功！");
            return "redirect:/admin/users";
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
            return "redirect:/admin/users/edit/" + id;
        }
    }

    @GetMapping("/change-password/{id}")
    public String showChangePasswordForm(@PathVariable Long id, Model model) {
        User user = userService.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在"));
        model.addAttribute("user", user);
        return "admin/user-change-password";
    }

    @PostMapping("/change-password/{id}")
    public String changePassword(@PathVariable Long id,
                               @RequestParam String newPassword,
                               @RequestParam String confirmPassword,
                               RedirectAttributes redirectAttributes) {
        try {
            if (!newPassword.equals(confirmPassword)) {
                redirectAttributes.addFlashAttribute("errorMessage", "两次输入的密码不一致");
                return "redirect:/admin/users/change-password/" + id;
            }
            
            userService.updateUserPassword(id, newPassword);
            redirectAttributes.addFlashAttribute("successMessage", "密码修改成功！");
            return "redirect:/admin/users";
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
            return "redirect:/admin/users/change-password/" + id;
        }
    }

    @PostMapping("/delete/{id}")
    public String deleteUser(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            userService.deleteUser(id);
            redirectAttributes.addFlashAttribute("successMessage", "用户删除成功！");
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        return "redirect:/admin/users";
    }
}
